package org.example.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyServerHandler extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(MyServerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        SocketChannel channel = (SocketChannel) ctx.channel();
        logger.info("[管道激活时]监听到有一客户端链接到服务端...服务端IP:{}，服务端端口:{}", channel.localAddress().getHostString()
                , channel.localAddress().getPort());
        ctx.writeAndFlush("您好，欢迎来到【Netty】世界！\r\n");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 这里我们已经不再需要自己手动进行解码了，因为Netty已经帮我们自动解码了
        logger.info("{} [服务端]接收到[客户端]消息：{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
                , msg);
        ctx.writeAndFlush(msg + "\r\n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        logger.info("{} [客户端]断开链接 服务端[{}}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
                , ctx.channel().localAddress().toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
        System.out.println("异常信息：\r\n" + cause.getMessage());
    }
}
